/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState } from 'react';
import { Button, Form, InputNumber, Space, message, Typography, Card } from 'antd';
import { ProFormCheckbox } from '@ant-design/pro-form';
import KbEditForm from '../KbEditForm';
import type { ConnectState } from '@/models/connect';
import type { OptionsType } from '@/components/_pages/jdk/addLeague/_utils/type';
import {
  getFreightConfigInfo,
  saveFreightConfigSave,
  getFreeServiceFeeBrandList,
  setFreeServiceFeeBrandList,
} from '@/services/jdk/league';
import { useSelector } from 'umi';
import {
  getPlatformRatio,
  getPriceRender,
  getRatioStorage,
  getRatioRender,
  getPriceStorage,
} from '../../_utils/index';
import styles from './index.less';
import { isArray, difference } from 'lodash';

const { Item } = Form;
const { Title, Text } = Typography;
interface KbDrawer {
  league_id: string;
}

const formatLadderPrice = (data: any[], type: 'get' | 'set', price?: number) => {
  if (isArray(data) && data.length > 0) {
    const lastItem = data[data.length - 1];
    switch (type) {
      case 'get':
        return getPriceRender(lastItem.price);
      case 'set':
        if (lastItem.price) {
          lastItem.price = getPriceStorage(price);
          return data;
        }
        return 0;
      default:
        return 0;
    }
  } else {
    return 0;
  }
};
const Index = ({ league_id }: KbDrawer) => {
  const [form] = Form.useForm();
  const [formData_1, setFormData_1] = useState<any>({ ladder_price: [] });
  const [formData_2, setFormData_2] = useState<any>();
  const [formData_3, setFormData_3] = useState<any>();
  const [formData_4, setFormData_4] = useState<any>({ ladder_price: [] });
  const [leagueId, setleagueId] = useState('');
  const [leagueOptions, setLeagueOptions] = useState<OptionsType[]>([]);
  const [leaguePlatOptions, setLeaguePlatOptions] = useState<OptionsType[]>([]);
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const queryData = (param: { league_id: string }) => {
    getFreightConfigInfo(param).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        setFormData_1(data['1']);
        setFormData_2(data['2']);
        setFormData_3(data['3']);
        setFormData_4(data['4']);
        const { base_price: base_price_1, ladder_price: ladder_price_1 } = data['1'];
        const { base_price: base_price_2, ladder_price: ladder_price_2 } = data['2'];
        const { ratio } = data['3'];
        const { ladder_price: ladder_price_4 } = data['4'];
        const [platformRatio, providerRatio] = getPlatformRatio(ratio);
        const ladderPrice_1 = ladder_price_1.map((item: any) => ({
          ...item,
          ratio: getRatioRender(item.ratio),
        }));
        const advancePrice = formatLadderPrice(ladder_price_2, 'get');
        const ladderPrice_4 = ladder_price_4.map((item: any) => ({
          ...item,
          price: getPriceRender(item.price),
        }));
        form.setFieldsValue({
          base_price_1: getPriceRender(base_price_1),
          base_price_2: getPriceRender(base_price_2),
          advancePrice,
          platformRatio,
          providerRatio,
          ladder_price_1: ladderPrice_1,
          ladder_price_4: ladderPrice_4,
        });
      } else {
        message.error(msg);
      }
    });
  };
  const filterBrand = (data: any[], key: string) =>
    data.filter((item) => item[key] == '0').map((item) => item.value);
  const getFreeList = () => {
    getFreeServiceFeeBrandList({ league_id }).then((data: OptionsType[]) => {
      const optionList = data.filter((item) => item.type == '0');
      const platOptionList = data.filter((item) => item.type == '1');
      form.setFieldsValue({
        delivery: filterBrand(optionList, 'free'),
        platDelivery: filterBrand(platOptionList, 'free'),
      });
      setLeagueOptions(optionList);
      setLeaguePlatOptions(platOptionList);
    });
  };
  const onSubmit = async (values: any) => {
    const {
      base_price_1,
      base_price_2,
      advancePrice,
      providerRatio,
      platformRatio,
      ladder_price_1,
      ladder_price_4,
      delivery,
      platDelivery,
    } = values;
    const feeBrandList = difference(
      leagueOptions.map((item) => item.value),
      delivery,
    );
    const platformBrandList = difference(
      leaguePlatOptions.map((item) => item.value),
      platDelivery,
    );
    setFreeServiceFeeBrandList({
      league_id,
      brand_list: JSON.stringify(feeBrandList),
      platform_brand_list: JSON.stringify(platformBrandList),
    }).then(({ code }) => {
      if (code !== 0) {
        getFreeList();
      }
    });
    if (providerRatio + platformRatio !== 10) {
      message.error('佣金比例错误');
      return;
    }
    const ladderPriceStorage_1 = ladder_price_1.map((item: any) => ({
      ...item,
      ratio: getRatioStorage(item.ratio),
    }));
    const ladderPriceStorage_2 = formatLadderPrice(formData_2.ladder_price, 'set', advancePrice);
    const ladderPriceStorage_4 = ladder_price_4.map((item: any) => ({
      ...item,
      price: getPriceStorage(item.price),
    }));
    const tpyeData_1 = {
      league_id,
      id: formData_1.id,
      type: '1',
      base_price: getPriceStorage(base_price_1),
      ladder_price: ladderPriceStorage_1,
    };
    const typeData_2 = {
      league_id,
      id: formData_2.id,
      type: '2',
      base_price: getPriceStorage(base_price_2),
      ladder_price: ladderPriceStorage_2,
    };
    const typeData_3 = {
      league_id,
      id: formData_3.id,
      type: '3',
      ratio: providerRatio * 10,
    };
    const typeData_4 = {
      league_id,
      id: formData_4.id,
      type: '4',
      ladder_price: ladderPriceStorage_4,
    };
    const requestData = [tpyeData_1, typeData_2, typeData_3, typeData_4];
    saveFreightConfigSave({ is_batch: '1', config: JSON.stringify(requestData) }).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        message.success(msg);
      } else if (code == 99999) {
        //部分保存成功需重新拉去已保存数据id
        message.error(
          <Space direction='vertical'>
            {isArray(data)
              ? data.map((item) => {
                  return <span>{item}</span>;
                })
              : msg}
          </Space>,
        );
        queryData({ league_id });
      } else {
        message.error(msg);
      }
    });
  };

  useEffect(() => {
    if (league_id && league_id !== leagueId) {
      setleagueId(league_id);
      queryData({ league_id });
      getFreeList();
    }
  }, [league_id]);
  return (
    <Card title={<Title level={5}>佣金设置</Title>} className={styles.KbDrawer}>
      <Form form={form} onFinish={onSubmit}>
        <Space direction={winSize === 'xxl' ? 'horizontal' : 'vertical'} align='start'>
          <div>
            <Item colon={false} label={[<Text key='self'>自运力佣金设置</Text>]}>
              <Text>（基础价格、分佣比例、阶梯价格默认值支持修改）</Text>
            </Item>
            <Item label='基础价格' name='base_price_1'>
              <InputNumber addonAfter='元/单' min={0} style={{ width: 200, marginBottom: 8 }} />
            </Item>
            <Item label='阶梯价格'>
              <KbEditForm type='selfTransport' />
            </Item>

            <Item label='佣金比例:'>
              <Space>
                <Item name='providerRatio'>
                  <InputNumber addonBefore='服务商' min={0} max={10} style={{ width: 150 }} />
                </Item>
                <Item>:</Item>
                <Item name='platformRatio'>
                  <InputNumber addonBefore=' 平台' min={0} max={10} style={{ width: 150 }} />
                </Item>
              </Space>
            </Item>
            <Item>
              <ProFormCheckbox.Group
                label='适用自运力'
                labelCol={{ span: 24 }}
                name='delivery'
                fieldProps={{
                  options: leagueOptions,
                }}
              />
            </Item>
          </div>
          <div>
            <Item label={[<Text key='plat'>平台运力佣金设置</Text>]}></Item>
            <Item label='基础价格' name='base_price_2'>
              <InputNumber addonAfter='元/单' min={0} style={{ width: 200, marginBottom: 8 }} />
            </Item>
            <Space>
              <Item label='里程加价' name='advancePrice' extra='（超过3公里，每公里加价）'>
                <InputNumber addonAfter='元' min={0} style={{ width: 200, marginBottom: 8 }} />
              </Item>
            </Space>
            <Item label='阶梯价格'>
              <KbEditForm type='platform' />
            </Item>
            <Item>
              <ProFormCheckbox.Group
                label='适用平台运力'
                labelCol={{ span: 24 }}
                name='platDelivery'
                fieldProps={{
                  options: leaguePlatOptions,
                }}
              />
            </Item>
          </div>
        </Space>

        <Item>
          <Space align='end'>
            <Button type='primary' htmlType='submit'>
              保存
            </Button>
            <div style={{ color: 'red' }}>
              注：初始按照基础价格执行，阶梯价格根据上月平均单量来执行
            </div>
          </Space>
        </Item>
      </Form>
    </Card>
  );
};

export default Index;
